import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import { FrameSty, ImgSty, NameSty } from './style'


export interface WaterfallFlowItemProps {
  /** 显示边界*/
  showBorder: number
  src: string,
  title: string,
  style: React.CSSProperties,
  unitWidth: number,
  index: number,
  sizeChange?: (height: number, index: number) => void
}

export default function Index(props: WaterfallFlowItemProps) {
  let { src, title, style = {}, sizeChange = () => { }, unitWidth, index, showBorder } = props
  let frameDom = useRef(null)
  let [isLoading, setIsLoading] = useState(false)
  let [imgInfo, setImgInfo] = useState<{
    height: number,
    width: number
  }>({
    height: 1,
    width: 1
  })
  let imgDom = useRef<any>(null)
  /** 是否初始化完成*/
  let isInitAccomplish = useRef(false)

  /** 离父亲上边框的距离*/
  let top = useMemo(() => {
    let y = style.transform ? Number(style.transform?.substring(style.transform.indexOf(',', 0) + 1, style.transform.length - 3)) : undefined
    return y
  }, [style])

  /** 是否加载图片*/
  let isImgShow = useMemo(() => {
    if (top === undefined) {
      return false
    }
    if (top <= showBorder) {
      return true
    } else {
      return false
    }
  }, [top, showBorder])

  const imgHeight = useMemo(() => {
    return imgInfo.height * (unitWidth / imgInfo.width);
  }, [imgInfo, unitWidth])

  /** 符合条件懒加载图片*/
  useEffect(() => {
    if (isInitAccomplish.current) {
      return
    }
    if (imgDom.current === null || src === '' || isImgShow === false) {
      return
    }
    let img = new Image();
    img.src = src;
    img.onload = () => {
      setImgInfo({
        height: img.height,
        width: img.width,
      })
      setIsLoading(true)
    }
    imgDom.current.src = src
    isInitAccomplish.current = true
  }, [src, isImgShow])

  useEffect(() => {
    isInitAccomplish.current && sizeChange(imgHeight + 40, index)
  }, [imgHeight, index])

  return (
    <FrameSty style={{
      ...style,
    }} ref={frameDom}>
      <ImgSty>
        {
          <img ref={imgDom}
            style={{
              visibility: isLoading ? 'visible' : 'hidden'
            }}
          />
        }
      </ImgSty>
      <NameSty>
        {title && title}
      </NameSty>
    </FrameSty>
  )
}